package com.ziytek.web.citizen.model.bean;

import com.ziytek.web.citizen.constant.NumConstant;
import com.ziytek.web.citizen.util.HexUtil;
import com.ziytek.web.citizen.util.StringUtil;
import com.ziytek.web.citizen.util.XorDataUtils;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * @author fenghx
 * @version v1.0
 * @className LightControl
 * @descripton 功能描述
 * @date 2023/7/12 13:46
 **/

@Data
@Slf4j
public class CapacityControl {

    /***
     * 分控版地址
     * */
    private String controlAddress;
    /***
     * key:电芯位置 value:电池容量
     * */
    private Map<Integer, Float> capacityMap;

    public void setCapacityMapData(int position, float capacity) {
        if (CollectionUtils.isEmpty(capacityMap)) {
            capacityMap = new HashMap<>();
        }
        capacityMap.put(position, capacity);
    }

    public String getSendData(String address, String data) {
        if (StringUtil.isEmpty(address) || StringUtil.isEmpty(data)) {
            return null;
        }

        CapacityProtocol capacityProtocol = new CapacityProtocol();
        capacityProtocol.setBoardAddress(address);
        // 充放电负载有效数据长度
        capacityProtocol.setData(data);
        int buffLen = (data.length()) / NumConstant.INT_TWO;
        // 负载有效数据长度
        capacityProtocol.setDataLen(HexUtil.fillZero(String.format("%04x", buffLen), NumConstant.INT_FOUR));

        String xorData = capacityProtocol.getHeader()
                + capacityProtocol.getBoardAddress() + capacityProtocol.getDataType()
                + capacityProtocol.getDataLen() + capacityProtocol.getData();
        String xor = XorDataUtils.getXor(xorData.getBytes(StandardCharsets.UTF_8));
        capacityProtocol.setXor(xor.trim());

        String sendData = capacityProtocol.getAllData();
        sendData = sendData.replaceAll(" ", "");
        return sendData;
    }
}
